#include "stdafx.h"

#include "StateManager.h"
#include "InputManager.h"

float StateManager::execution_time = 0;
const float StateManager::update_time = 0.01;


bool StateManager::instanceFlag = false;
StateManager *StateManager::stateManager = NULL;


StateManager *StateManager::getInstance() {
	if (!instanceFlag) {
		stateManager = new StateManager();

		instanceFlag = true;
		return stateManager;
	}
	else
	{
		return stateManager;
	}	
}

StateManager::StateManager() {
	m_currentState = NULL;
	m_root = NULL;
	m_window = NULL;
	gameState = NULL;
	mainMenuState = NULL;
	//physics::physInitialize();
	m_shutdown = false;
	startGameStateFlag = false;
	replayMode = false;
	// Set the default IP here
	defaultIP = "127.0.0.1";
	ip = defaultIP;
}

void StateManager::setRoot(Ogre::Root* root) {
	m_root = root;
	root->addFrameListener(this);
	//TODO possible memory leak
}

Ogre::Root* StateManager::getRoot() {
	return m_root;
}

void StateManager::setWindow(Ogre::RenderWindow* window) {
	m_window = window;
}

Ogre::RenderWindow* StateManager::getWindow() {
	return m_window;
}

StateManager::~StateManager() {
	instanceFlag = false;

	// TEMP CODE?
	if(m_currentState)
	{
		//TODO WTF
		//delete m_currentState;
		m_currentState = NULL;
	}
	
}

bool StateManager::frameRenderingQueued(const Ogre::FrameEvent &evt) {	
	if (m_shutdown == true) {
		return false;
	}
	
	//Update input manager
	InputManager::getInstance()->captureInput();
	
	//update all controllers
	float deltaTime = evt.timeSinceLastFrame;
	execution_time += deltaTime;
	if(m_currentState) {
		if (execution_time > update_time) {
			return m_currentState->update(deltaTime);
			execution_time -= update_time;
		}
	}
	return true;
}

bool StateManager::frameEnded(const Ogre::FrameEvent &evt) {
	if (startGameStateFlag) {
		startGameState();
		startGameStateFlag = false;
	}
	return true;
}

void StateManager::quitGame() {
	m_shutdown = true;
}


void StateManager::startGame() {
	startGameState();
}


void StateManager::startMenuState() {
	if (gameState) {
		// m_currentState->clean();
		delete gameState;
//		state->initalize(m_window);
	}
	mainMenuState = new MainMenuState(m_root);
	mainMenuState->initalize(m_window);
	m_currentState = mainMenuState;
	
}

void StateManager::startGameStateFlagged(string receivedIP) {
	startGameStateFlag = true;
	if (receivedIP != ip) {
		ip = receivedIP;
	}
}

void StateManager::startGameState() {
	if (mainMenuState) {
		delete mainMenuState;
	}
	gameState = new GameState(ip, replayMode);
	gameState->initalize(m_window);
	m_currentState = gameState;
}

void StateManager::startReplayState() {
	replayMode = true;
	StateManager::startGameStateFlagged(defaultIP);
}